package com.fowo.api.common.mybatis.helper;

import net.sf.jsqlparser.expression.*;
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.expression.operators.relational.GreaterThan;
import net.sf.jsqlparser.statement.create.table.ColDataType;

/**
 * 分页搜索器 Sql Server 方言处理
 * @author yl_ls
 */
public class SqlServerPageSearchSqlDialect implements PageSearchSqlDialect {
    @Override
    public Expression stringSetFieldInExpression(Expression left, Expression right) {
        return new GreaterThan()
                .withLeftExpression(new Function().withName("CHARINDEX").withParameters(new ExpressionList().addExpressions(
                        new Function().withName("CONCAT").withParameters(new ExpressionList().addExpressions(
                                new StringValue(","),
                                right,
                                new StringValue(",")
                        )),
                        new Function().withName("CONCAT").withParameters(new ExpressionList().addExpressions(
                                new StringValue(","),
                                left,
                                new StringValue(",")
                        ))
                )))
                .withRightExpression(new LongValue(0));
    }

    @Override
    public Expression jsonArrayFieldInExpression(Expression left, Expression right) {
        return new EqualsTo()
                .withLeftExpression(new Function().withName("dbo.JSON_CONTAINS").withParameters(new ExpressionList().addExpressions(
                        left,
                        new CastExpression()
                                .withType(new ColDataType("CHAR"))
                                .withLeftExpression(right),
                        new StringValue("$")
                )))
                .withRightExpression(new LongValue(1));
    }
}
